<template>
  <div class="app-container">
    <PageSearch :showSearch.sync="showSearch" :getList="getList" :handleQuery="handleQuery" :resetQuery="resetQuery">
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="skuNo">
              <el-input
                v-model="queryParams.skuNo"
                :placeholder="$t('sku编号')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="janCode">
              <el-input
                v-model="queryParams.janCode"
                :placeholder="$t('jan编码')"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="skuNameCn">
              <el-input
                v-model="queryParams.skuNameCn"
                :placeholder="$t('商品(中文)')"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="skuNameEn">
              <el-input
                v-model="queryParams.skuNameEn"
                :placeholder="$t('商品(英文)')"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="skuNameJp">
              <el-input
                v-model="queryParams.skuNameJp"
                :placeholder="$t('商品(日文)')"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item prop="spNo">
              <el-input
                v-model="queryParams.spNo"
                :placeholder="$t('库位号')"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item prop="classId">
              <treeselect
                :appendToBody="true"
                style="width: 240px"
                v-model="queryParams.classId"
                :options="menuOptions"
                :show-count="true"
                :placeholder="$t('商品分类')"
              />
            </el-form-item>
            <!-- <el-form-item prop="janCode">
              <el-select
                clearable
                style="width: 240px"
                :placeholder="$t('日本发货方式')"
                v-model="queryParams.xxxx">
                <el-option :label="$t('1')" :value="1" />
                <el-option :label="$t('2')" :value="0" />
              </el-select>
            </el-form-item> -->
            <el-form-item prop="">
              <el-select clearable style="width: 240px" :placeholder="$t('sku状态')" v-model="queryParams.isApply">
                <el-option :label="$t('已申请')" :value="1" />
                <el-option :label="$t('未申请')" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item prop="classId">
              <el-select
                clearable
                style="width: 240px"
                :placeholder="$t('云库存是否大于0')"
                filterable
                v-model="queryParams.gtZero"
              >
                <el-option :label="$t('是')" :value="1" />
                <el-option :label="$t('否')" :value="0" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #pagination>
        <pagination
          v-show="pageTotal > 0"
          :total="pageTotal"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
    </PageSearch>
    <el-table
      @row-click="(row) => $rowClick(row, clickedRows)"
      :row-class-name="({ row }) => $tableRowClassName(row, clickedRows)"
      :height="calTableHeight()"
      v-loading="loading"
      ref="TableRef"
      :data="tableData"
      row-key="menuId"
    >
      <el-table-column align="center" width="150" show-overflow-tooltip prop="skuNo" :label="$t('sku编号')">
        <template #header="{ column }">
          <div class="sort-item">
            <div @click="resetSortQuery(column)">
              {{ column.label }}
            </div>
            <div class="sort-item-icon">
              <i
                class="el-icon-caret-top"
                @click="setSortQuery(column, 'asc')"
                :style="setSortIconStyle(column, 'asc')"
              />
              <i
                @click="setSortQuery(column, 'desc')"
                :style="setSortIconStyle(column, 'desc')"
                class="el-icon-caret-bottom"
              />
            </div>
          </div>
        </template>
        <template slot-scope="scope">
          <div @click="handleEdit(scope.row)" style="cursor: pointer; color: #1890ff">
            {{ scope.row.skuNo }}
          </div>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" show-overflow-tooltip prop="spNo" :label="$t('库位号')">
        <template #header="{ column }">
          <div class="sort-item">
            <div @click="resetSortQuery(column)">
              {{ column.label }}
            </div>
            <div class="sort-item-icon">
              <i
                class="el-icon-caret-top"
                @click="setSortQuery(column, 'asc')"
                :style="setSortIconStyle(column, 'asc')"
              />
              <i
                @click="setSortQuery(column, 'desc')"
                :style="setSortIconStyle(column, 'desc')"
                class="el-icon-caret-bottom"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('主图')" prop="imgUrl" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 50px; height: 50px"
            fit="contain"
            :key="Math.random()"
            v-hover="scope.row.imgUrl"
            :src="scope.row.imgUrl + '?x-oss-process=image/resize,w_100/quality,q_70'"
          />
        </template>
      </el-table-column>
      <el-table-column
        width="150"
        align="center"
        show-overflow-tooltip
        prop="janCode"
        :label="$t('jan编码')"
        custom-sort
      />
      <el-table-column width="150" align="center" show-overflow-tooltip prop="skuNameCn" :label="$t('中文名')" />
      <el-table-column width="150" align="center" show-overflow-tooltip prop="skuNameJp" :label="$t('日文名')" />
      <el-table-column align="center" show-overflow-tooltip prop="cloudStock" :label="$t('可申请数量')" width="100">
        <template #header="{ column }">
          <div class="sort-item">
            <div @click="resetSortQuery(column)">
              {{ column.label }}
            </div>
            <div class="sort-item-icon">
              <i
                class="el-icon-caret-top"
                @click="setSortQuery(column, 'asc')"
                :style="setSortIconStyle(column, 'asc')"
              />
              <i
                @click="setSortQuery(column, 'desc')"
                :style="setSortIconStyle(column, 'desc')"
                class="el-icon-caret-bottom"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="sellerStock" :label="$t('卖家库存数量')" width="100">
        <template slot-scope="{ row }">
          <span v-if="row.sellerStock == null" style="color: red">
            {{ $t('未申请') }}
          </span>
          <span v-else style="color: green">
            {{ row.sellerStock }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="cloudPrice" :label="$t('价格')">
        <template slot-scope="scope">
          {{ (+scope.row.cloudPrice).toFixed(0) }}
        </template>
      </el-table-column>

      <el-table-column show-overflow-tooltip :label="$t('更新日期')" align="center" prop="updateTime" width="150">
        <template #header="{ column }">
          <div class="sort-item">
            <div @click="resetSortQuery(column)">
              {{ column.label }}
            </div>
            <div class="sort-item-icon">
              <i
                class="el-icon-caret-top"
                @click="setSortQuery(column, 'asc')"
                :style="setSortIconStyle(column, 'asc')"
              />
              <i
                @click="setSortQuery(column, 'desc')"
                :style="setSortIconStyle(column, 'desc')"
                class="el-icon-caret-bottom"
              />
            </div>
          </div>
        </template>
        <template slot-scope="{ row }">
          <div style="color: red">
            <!-- sku类型：0-不显示 1-新品 2-补货 -->
            <img v-if="row.goodsTag == 1" style="width: 80px" src="@/assets/images/new_product.png" alt="" />
            <img v-if="row.goodsTag == 2" style="width: 60px" src="@/assets/images/bu_huo.png" alt="" />
            <div style="color: #000">{{ row.shelfTime }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip prop="isApplyNum" width="150" :label="$t('申请中数量')">
        <template slot="header">
          <div>
            {{ $t('申请中数量') }}
            <el-tooltip effect="dark" placement="top-start">
              <div slot="content">
                <span>所有卖家申请中数量(未审批数量)</span>
              </div>
              <i style="cursor: pointer" class="el-icon-info"></i>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <!-- 备注 -->
      <el-table-column show-overflow-tooltip :label="$t('备注')" width="100" align="center" prop="remark" />

      <el-table-column fixed="right" :label="$t('操作')" align="center">
        <template slot="header">
          <div>
            {{ $t('操作') }}
            <el-tooltip effect="dark" placement="top-start">
              <div slot="content">
                <p>{{ $t('申请限制') }}：</p>
                <p>
                  {{ $t('1.已经申请过的sku没卖完或者没卖超过申请数量一半，禁止继续申请') }}
                </p>
                <p>
                  {{
                    $t(
                      '例如：J-(00000006)申请了20，如果付款数量没超过10个就不能继续申请，付款数量会在销售、提前付款、周期结账时更新。',
                    )
                  }}
                </p>
                <p>
                  {{
                    $t(
                      '2.申请后如果觉得卖不完可以退回库存，可以选择数量，但是一个申请只能退回一次，并且退回数量大于一半会在卖家SKU库存表标记限制',
                    )
                  }}
                </p>
                <p>
                  {{ $t('被标记限制的sku申请时，只能申请月销售数量') }}
                </p>
                <p>
                  {{
                    $t(
                      '例如：J-(00000006)申请了20，如果退回了10个就会被标记限制，限制后如果还想申请，只能申请等于或小于该sku的月销量的数量，或者向管理员提出解除限制',
                    )
                  }}
                </p>
              </div>
              <i style="cursor: pointer" class="el-icon-info"></i>
            </el-tooltip>
          </div>
        </template>
        <template slot-scope="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <span class="el-dropdown-link">
              {{ $t('更多') }}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <!-- isApply  0 未申请 1 已申请 -->
              <el-dropdown-item
                :disabled="row.isApply == 1"
                v-hasPermi="['distribution:skuSellerApply:init']"
                command="handleInit"
              >
                {{ $t('初始化sku') }}
              </el-dropdown-item>
              <!-- cloudStock 可申请数量为0不能申请 -->
              <el-dropdown-item
                :disabled="row.cloudStock == 0"
                v-hasPermi="['distribution:skuSellerApply:apply']"
                command="applyStock"
              >
                {{ $t('申请库存') }}
              </el-dropdown-item>
              <!-- isApply  0 未申请 1 已申请  未申请不能预约 -->
              <el-dropdown-item
                :disabled="row.isApply != 1"
                v-hasPermi="['distribution:skuDistributor:reservationSku']"
                command="handleReservationSku"
              >
                {{ $t('预约库存') }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="pageTotal > 0"
      :total="pageTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 申请 -->
    <el-dialog
      :visible.sync="editDialogConfig"
      :title="$t('申请数量')"
      top="7vh"
      width="1500px"
      :before-close="close"
      destroy-on-close
      :modal="true"
      :close-on-click-modal="false"
      class="articleModal"
    >
      <div class="apply-num">
        <el-form ref="elForm" :model="curentData" :rules="curentDataRuler" size="small" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="id" prop="id">
                <el-input disabled v-model="curentData.id" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('sku编号')" prop="skuNo">
                <el-input disabled v-model="curentData.skuNo" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('中文名')" prop="skuNameCn">
                <el-input disabled v-model="curentData.skuNameCn" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('日文名')" prop="skuNameJp">
                <el-input disabled v-model="curentData.skuNameJp" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('价格')" prop="cloudPrice">
                <el-input class="color-red" disabled v-model="curentData.cloudPrice" :placeholder="$t('请输入')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('供应商名称')" prop="distrName">
                <el-input disabled v-model="curentData.distrName" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('更新日期')" prop="updateTime">
                <el-input disabled v-model="curentData.updateTime" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('备注')" prop="remark">
                <el-input disabled v-model="curentData.remark" :placeholder="$t('请输入')" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('申请数量')" prop="applyNum">
                <el-input type="number" v-model.number="curentData.applyNum" clearable />
                <!-- <el-input-number style="width: 100%;" :precision="0" v-model="curentData.applyNum" controls-position="right" :min="0" :max="curentData.cloudStock" /> -->
                <!-- <el-input-number
                  style="width: 100%"
                  v-model="curentData.applyNum"
                  controls-position="right"
                  :precision="0"
                  :min="1"
                  :max="curentData.cloudStock" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('可申请数量')">
                <el-input disabled v-model="curentData.cloudStock" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="curentData.sellerLevelName">
            <el-col :span="12">
              <el-form-item :label="$t('卖家级别')" style="color: red">
                {{ `${curentData.sellerLevelName}  (自动审批比例： ${curentData.sellerLevelRate}%)` }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="apply-num-table">
          <header>{{ $t('历史申请记录') }}</header>
          <el-table ref="TableRef" :data="curentTableData">
            <el-table-column show-overflow-tooltip align="center" :label="$t('sku')" prop="skuNo" width="150" />
            <el-table-column show-overflow-tooltip align="center" :label="$t('申请时价格')" prop="applyPrice">
              <template #default="{ row }">
                <div style="color: red; font-weight: bold">{{ row.applyPrice | thousand }}</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip align="center" :label="$t('申请数量')" prop="applyNum" />
            <el-table-column show-overflow-tooltip align="center" :label="$t('剩下可用数量')" prop="useNum" />
            <el-table-column show-overflow-tooltip align="center" :label="$t('出售数量')" prop="saleNum" />
            <el-table-column show-overflow-tooltip align="center" :label="$t('待出账单')" prop="waitBillNum" />
            <el-table-column show-overflow-tooltip align="center" :label="$t('付款数量')" prop="payNum" />
            <el-table-column
              show-overflow-tooltip
              align="center"
              :label="$t('申请时间')"
              prop="applyTime"
              width="150"
            />
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('确定') }}</el-button>
        <el-button @click="close">{{ $t('取消') }}</el-button>
      </div>
    </el-dialog>
    <!-- sku详情/修改 -->
    <Skucontmoduler @relaod="relaod" :isShowAll="false" ref="Skucontmoduler"></Skucontmoduler>
    <!-- 预约库存 -->
    <ReservationSku :show.sync="reservationSku.show" :formData="reservationSku.formData" @getList="getList" />
  </div>
</template>

<script>
import {
  init,
  skuDistributorGetCloudList,
  skuDistributorSellerApply,
  getHistoryApplyList,
} from '@/api/distribution/sku/cloudProduct'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import ReservationSku from './components/reservationSku.vue'

export default {
  components: { Treeselect, ReservationSku },
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
    if (this.$route.query.goToBeforePaySku) {
      this.queryParams.skuNo = JSON.parse(JSON.stringify(this.$route.query.goToBeforePaySku))
      this.showSearch = true
      setTimeout(() => {
        this.getList()
      }, 500)
    }
  },
  mounted() {
    if (this.$route.query.goToBeforePaySku) {
      this.queryParams.skuNo = JSON.parse(JSON.stringify(this.$route.query.goToBeforePaySku))
      this.showSearch = true
      setTimeout(() => {
        this.getList()
      }, 500)
    }
  },
  name: 'CloudProduct',

  data() {
    return {
      reservationSku: {
        show: false,
        formData: {},
      },
      /**点击的表格项 */
      clickedRows: [],
      /**商品分类菜单树选项 */
      menuOptions: [],
      showSearch: false,
      curentData: {
        label: '',
        skuId: '',
        skuNo: '',
        imgUr: '',
        skuNameCn: '',
        skuNameJp: '',
        cloudStock: '',
        cloudPrice: '',
        distrName: '',
        updateTime: '',
        remark: '',
      },
      curentDataRuler: {
        applyNum: [],
      },
      curentTableData: [],
      editDialogConfig: false,
      tableData: [],
      /**数据总条数 */
      pageTotal: 0,
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        skuNo: '',
      },
    }
  },
  watch: {
    'queryParams.pageNum': function (val) {
      this.clickedRows = []
    },
  },
  created() {
    this.getList()
    this.$getSkuClassList().then((res) => {
      this.menuOptions = res.menuOptions
    })
  },

  methods: {
    /**预约库存 */
    handleReservationSku(row) {
      this.reservationSku.formData = { ...row }
      this.reservationSku.show = true
    },
    handleCommand(command, row) {
      this[command](row)
    },
    handleInit(row) {
      this.$confirm('确定初始化?', this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        const data = {
          ...row,
        }
        init(data).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })

            this.getList()
          }
        })
      })
    },
    relaod() {
      this.getList()
    },
    handleEdit(row) {
      this.$refs.Skucontmoduler.setSkuInfo(row)
      this.$refs.Skucontmoduler.checkNumber('basicInformationSeller')
    },
    // 取消申请
    close() {
      this.curentData = {}
      this.editDialogConfig = !this.editDialogConfig
    },
    // 提交申请
    submitForm() {
      this.$refs.elForm.validate((valid) => {
        if (valid) {
          this.curentData.applyNum = this.curentData.applyNum
          this.curentData.applyPrice = this.curentData.cloudPrice
          this.curentData.applyDistrId = this.curentData.distrId
          if (this.curentData.applyNum == 0) {
            return this.$message.error('申请数量应大于0')
          }
          skuDistributorSellerApply(this.curentData).then((res) => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: res.msg,
              })
              this.editDialogConfig = !this.editDialogConfig
              this.getList()
            } else {
              this.getList()
            }
          })
        }
      })
    },
    // 展示申请
    applyStock(row) {
      const data = JSON.parse(JSON.stringify(row))
      this.curentDataRuler.applyNum = [
        {
          type: 'number',
          min: 0,
          max: data.cloudStock,
          message: `请输入1-${data.cloudStock}数量`,
          trigger: 'blur',
        },
        {
          required: true,
          message: '请输入申请数量',
          trigger: 'blur',
        },
      ]
      this.curentData = data
      // this.curentData.cloudPrice = (data.cloudPrice * 1.1).toFixed(0)
      getHistoryApplyList(row.skuId).then((res) => {
        this.curentTableData = res.data
      })
      this.curentData.cloudPrice = (+data.cloudPrice).toFixed(0)
      this.editDialogConfig = !this.editDialogConfig
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true
      skuDistributorGetCloudList(this.queryParams).then((res) => {
        this.tableData = res.rows || []
        this.pageTotal = res.total
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.value1 = null
      Object.keys(this.queryParams).forEach((key) => {
        this.queryParams[key] = null
      })
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10

      this.getList()
    },
  },
}
</script>
<style lang="scss" scoped>
.apply-num {
  display: flex;
  gap: 20px;
  &-table {
    header {
      margin-top: -25px;
      margin-bottom: 10px;
      font-weight: 600;
    }
    flex: 1;
  }
}

.color-red {
  ::v-deep .el-input__inner {
    color: red;
    font-weight: bold;
  }
}
</style>
